package com.example.forum.controller;

import com.example.forum.commen.AppResult;
import com.example.forum.commen.ResultCode;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Board;
import com.example.forum.services.IBoardService;
import jakarta.annotation.Resource;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/board")
public class BoardController {

    //从配置文件读取数值，如果没有配置，默认值为9
    @Value("${example-forum.index.board-num:9}")
    private Integer indexBoardNum;
    @Resource
    private IBoardService boardService;
    /*
    * 查询首页列表
    * */
    @GetMapping("topList")
    public AppResult<List<Board>> topList() {
        log.info("首页个数为："+indexBoardNum);
        //调用Serevice查询结果
        List<Board> boards = boardService.selectByNum(indexBoardNum);
        ///判断是否为空
        if(boards == null) {
            boards = new ArrayList<>();
        }
        //返回结果
        return AppResult.success(boards);
    }
    @GetMapping("/getById")
    private AppResult<Board>  getById(@RequestParam("id") @NonNull Long id) {
        //调用service
        Board board = boardService.selectByPrimaryKey(id);
        //对结果查询
        if(board == null || board.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_BOARDNOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARDNOT_EXISTS));
        }
        //返回结果
        return AppResult.success(board);
    }
}
